package com.yao;

import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import com.yao.common.Startup;
import com.yao.entity.Dish;

/**
 * 第四章 - 流
 * 
 * @author yaoym
 * @date 2018年1月30日 下午3:18:08
 * @version V1.0
 */
public class SessionFourth {

	static List<Dish> menu;

	/**
	 * 数据初始化
	 */
	static {
		menu = Startup.getMenu();
	}

	public static void main(String[] args) {
		// menu.stream()

		List<String> threeHighCaloricDishNames = menu.stream()
				.filter(d -> d.getCalories() > 300)
				.map(d -> d.getName())
				.limit(3)
				.collect(toList());
		
		//素菜
		List<Dish> vegetarianDishes = menu.stream().filter(Dish::isVegetarian).collect(toList());
		
		List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
		//偶数
		numbers.stream()
			.filter(i -> i % 2 == 0)
			.distinct()
			.skip(1)
			.limit(numbers.size())
			.forEach(System.out::println);
		
		menu.stream().filter(d -> d.getType() == Dish.Type.MEAT)
		.limit(2)
		.collect(toList());
		
		
		numbers = Arrays.asList(1, 2, 3, 4, 5);
		
		numbers.stream()
		.map(i -> i*i)
		.forEach(System.out::println);
	

		System.out.println();
		
		List<Integer> numbers1 = Arrays.asList(4, 5);
		List<Integer> numbers2 = Arrays.asList(3, 8);
		
		numbers1.stream().flatMap(i -> 
			numbers2.stream()
			.filter(j -> (i + j) % 3 == 0)
			.map(j -> new int[]{i, j})
		)
		.forEach( a -> {
			for (Integer b : a) {
				System.out.print(b+",");
			}
			System.out.println();
		});
		
		System.out.println();

		Optional<Dish> dish = menu.stream().filter(Dish::isVegetarian).findAny();
		menu.stream()
		.filter( d -> d.getName().equals("aaa"))
		.findAny()
		.ifPresent(d -> System.out.println(d.getName()));
		
		dish.ifPresent(dish1 -> {
			
			System.out.println(dish1);
		});
		
		System.out.println(dish.orElse(menu.get(2)));
		
		System.out.println(dish.isPresent());

		numbers.stream().reduce((a, b)-> a + b).ifPresent(sum -> System.out.println(sum));
		
		numbers.stream().reduce((a, b)-> Integer.min(a, b)).ifPresent(sum -> System.out.println(sum));
		

		numbers.stream().reduce(Integer::max).ifPresent(max -> System.out.println(max));
		numbers.stream().reduce(Integer::min).ifPresent(min -> System.out.println(min));
		
		//计算菜单有多少个菜
		
		menu.stream().map(d -> 1).reduce(Integer::sum).ifPresent(sum -> System.out.println("菜肴数："+sum));
		
		//计算卡路里综合
		int calories = menu.stream().mapToInt(Dish::getCalories).sum();
		
		//标准流与特化流之间转换
		IntStream intStream = menu.stream().mapToInt(Dish::getCalories);
		
		Stream<Integer> stream = intStream.boxed();
		
		
		//求最大
//		OptionalInt maxCalories = intStream.max();
//		maxCalories.orElse(1);
		
		IntStream.rangeClosed(1, 10).forEachOrdered(System.out::println);;
		
		
		
	}

	

	// 筛选卡路里小于400的菜品并且排序

}
